package edu.gyc.hiseckill.controller;


import edu.gyc.hiseckill.error.BusinessErrorEnum;
import edu.gyc.hiseckill.error.BusinessException;
import edu.gyc.hiseckill.model.CommonReturnType;
import edu.gyc.hiseckill.model.UserInfo;
import edu.gyc.hiseckill.model.UserOrder;
import edu.gyc.hiseckill.service.UserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ls
 * @since 2020-01-28
 */
@RestController
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RequestMapping("/order")
public class UserOrderController {
    @Autowired
    private UserOrderService userOrderService;

    @PostMapping("/createorder")
    public CommonReturnType createOrder(@RequestParam(name = "itemId") Integer itemId,
                                        @RequestParam(name = "amount") Integer amount,
                                        @RequestParam(name = "promoId",defaultValue = "0") Integer promoId,
                                        HttpSession session) throws BusinessException {
        UserOrder userOrder=new UserOrder();
        userOrder.setItemId(itemId);
        userOrder.setAmount(amount);
        if(promoId==0)
              userOrder.setPromoId(null);
        else
            userOrder.setPromoId(promoId);

      Boolean isLogin=(Boolean)  session.getAttribute("IS_LOGIN");
        if (isLogin==null||!isLogin) {
            throw new BusinessException(BusinessErrorEnum.USER_NOT_LOGIN);

        }

        UserInfo userInfo = (UserInfo) session.getAttribute("LOGIN_USER");

        userOrder.setUserId(userInfo.getId());
        userOrderService.createOrder(userOrder);

        return CommonReturnType.create(userInfo.getUsername()+"下单成功，静候服务吧！");
    }

}

